package com.heisen.security.holder;

import com.heisen.base.entity.SystemUser;
import com.heisen.base.utils.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Collection;
import java.util.LinkedHashMap;

/**
 * @author sen
 * @description
 * @date 2024/1/3 16:23
 */
@Slf4j
public class LoginUserContextHolder {


    /**
     * 获取用户信息
     *
     * @return SystemUser 当前用户信息
     */
    public static SystemUser getSysUser() {
        try {
            LinkedHashMap<String, Object> authenticationDetails = getAuthenticationDetails();
            // 是不是客户端登入
           // Boolean isclient = (Boolean) authenticationDetails.get("clientOnly");
            Object principal = authenticationDetails.get("principal");
           // Object userType = authenticationDetails.get("userType");

            return      GsonUtils.objToBean(principal, SystemUser.class);

        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return null;
        }
    }

    /**
     *  获取用户id
     * @return
     */
    public static Long getUserId() {
        return getSysUser() == null ? null : getSysUser().getUserId();
    }

    /**
     *  获取用户名
     * @return
     */
    public static String getUsername() {
        return getSysUser() == null ? null : getSysUser().getUsername();
    }

    /**
     *  获取电话
     * @return
     */
    public static String getMobile() {
        return getSysUser() == null ? null : getSysUser().getMobile();
    }

    /**
     * 获取当前用户权限集
     *
     * @return Collection<GrantedAuthority>权限集
     */
    public static Collection<GrantedAuthority> getSysUserAuthority() {
        return getOauth2Authentication().getAuthorities();
    }

    /**
     * 通过  上下文对象
     * @return
     */
    private static OAuth2Authentication getOauth2Authentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (OAuth2Authentication) authentication;
    }

    @SuppressWarnings("all")
    private static LinkedHashMap<String, Object> getAuthenticationDetails() {
        return (LinkedHashMap<String, Object>) getOauth2Authentication().getUserAuthentication().getDetails();
    }
    
}
